package com.bf.util;

import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import com.bf.entity.CustomForm;
import com.bf.free.FreeMarkerUtil;
import com.bf.service.CustomFormService;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class DynaFormFunction {
	private static CustomFormService cfs;
	private static String defaultTemplate = "cwbx.ftl";

	public static String form(Integer id) {
		try {
			CustomForm form = cfs.findById(id);
			if (form == null) {
				return null;
			}
			Configuration cfg = FreeMarkerUtil.getConfiguration();
			Template template = null;
			if (form.getTemplate() == null
					|| form.getTemplate().trim().equals("")) {
				template = cfg.getTemplate(defaultTemplate);
			} else {
				template = cfg.getTemplate(form.getTemplate());
			}
			//Writer out = new StringWriter();
			Writer out = new OutputStreamWriter(System.out);
			Map<String, Object> root = new HashMap<String, Object>();
			root.put("form", form);
			template.process(root, out);
			out.flush();
			//System.out.println(out.toString());
			return "hello";
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public void setCfs(CustomFormService cfs) {
		DynaFormFunction.cfs = cfs;
	}

	public static void setDefaultTemplate(String defaultTemplate) {
		DynaFormFunction.defaultTemplate = defaultTemplate;
	}
}
